package com.hcbd.tdwt.ui.htct.activity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Html;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hcbd.tdwt.R;
import com.hcbd.tdwt.base.bd.BdToolFactory;
import com.cy.translucentparent.StatusNavUtils;
import com.hcbd.tdwt.MainApp;

import com.hcbd.tdwt.base.AudioTrackManager;
import com.hcbd.tdwt.base.BaseActivity;
import com.hcbd.tdwt.base.BdManager;
import com.hcbd.tdwt.base.BeidouBoxParams;
import com.hcbd.tdwt.base.Constant;
import com.hcbd.tdwt.base.ConvertToBdMsgTool;
import com.hcbd.tdwt.base.ConvertToUserMsgTool;
import com.hcbd.tdwt.base.GlobalParams;
import com.hcbd.tdwt.base.ImgSendManager;
import com.hcbd.tdwt.base.Listener.SoftKeyBoardListener;
import com.hcbd.tdwt.util.BDToGPS;
import com.hcbd.tdwt.util.DateUtils;
import com.hcbd.tdwt.util.FileUtils;
import com.hcbd.tdwt.util.SharedPreferencesUtil;
import com.hcbd.tdwt.util.StringUtil;
import com.pangu.bdsdk2021.entity.terminalone.BDTXInfo;
import com.pangu.bdsdk2021.terminal.TerminalSendManager;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.hcbd.tdwt.ui.xingyu.activity.AddressBookActivity_;
import com.hcbd.tdwt.ui.xingyu.activity.ChatViewPictureActivity_;
import com.hcbd.tdwt.ui.xingyu.activity.PictureViewActivity_;
import com.hcbd.tdwt.ui.xingyu.adapter.MsgAdapter;
import com.hcbd.tdwt.ui.xingyu.dialog.ChooseMapPopupWindow;
import com.hcbd.tdwt.ui.xingyu.dialog.VoiceDialog;
import com.hcbd.tdwt.ui.xingyu.vo.BoxContact;
import com.hcbd.tdwt.ui.xingyu.vo.ResultNumberVo;
import com.hcbd.tdwt.ui.xingyu.vo.UserMessageVO;
import com.hcbd.tdwt.ui.xingyu.vo.UserMessageVO_Table;
import org.androidannotations.annotations.AfterTextChange;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.CheckedChange;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.Touch;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.osmdroid.util.GeoPoint;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import static android.view.View.VISIBLE;
import static com.hcbd.tdwt.base.BeidouBoxParams.sendFreq;
import static com.hcbd.tdwt.base.GlobalParams.sendBeidouMsgSignalEnable;
import static java.lang.Thread.sleep;

@SuppressLint("NonConstantResourceId")
@EActivity(R.layout.activity_send_msg_fuda)
public class SendMsgActivity extends BaseActivity implements ChooseMapPopupWindow.SendMsgHandler{
    @ViewById(R.id.receive_address_edit)
    EditText address;
    @ViewById
    RecyclerView messageRV;
    @ViewById
    TextView title;
    @ViewById
    EditText sendMessageEdit;
    @ViewById
    TextView sendBtn;
    //输入字数
    @ViewById(R.id.last_input_content_tv)
    TextView lastInputContentTv;
    @ViewById(R.id.location_info_cb)
    CheckBox locationInfo;

    @ViewById
    CheckBox voice;
    @ViewById
    RelativeLayout inputArea;
    @ViewById
    Button voiceInputBtn;
    @ViewById
    TextView msgTypeTv;
    @ViewById
    LinearLayout customLL;
    @ViewById
    CheckBox shortcutsCB;
    @ViewById
    ImageView picture;
    @ViewById
    LinearLayout messageLL;
    @ViewById
    TextView receiveTipTv;

    private MsgAdapter msgAdapter;
    private List<UserMessageVO>msgList;
    private String receiverNumber;
    private Drawable sendBtnBlueDB;
    private Drawable sendBtnGrayDB;
    private SharedPreferencesUtil sp;
    private int entryMode=0;
    private VoiceDialog mVoiceDialog;

    private String sendMode;
    private int frePoint=2;
    private int max_text_size=0;
    //选择地图弹框
    private ChooseMapPopupWindow chooseMapPopupWindow;
    private int ova_width_hg;
    private int rec_width;
    private int rec_height;
    @AfterViews
    protected void init() {
        StatusNavUtils.setStatusBarColor(this,getColor(R.color.blue_300));
        initMsgRegister();
        msgList=new ArrayList<>();
        title.setText("短报文通信");
        receiverNumber=getIntent().getStringExtra("receiverNumber");
        String receiverName = getIntent().getStringExtra("receiverName");
        entryMode = getIntent().getIntExtra("entryMode",0);
        sp=new SharedPreferencesUtil(this);
        sendMode=sp.getAttribute(Constant.MSG_MODE);
        String point=sp.getAttribute(Constant.SEND_POINT_TYPE);
        if(Constant.POINT_THREE.equals(point)){
            frePoint=3;
        }
        max_text_size= BdManager.getInstance().send_size;
        sendMessageEdit.setFilters(new InputFilter[]{new InputFilter.LengthFilter(max_text_size)});
        lastInputContentTv.setText(MessageFormat.format("当前还可以输入{0}个字", max_text_size));
        if(receiverNumber==null){
            receiverNumber = sp.getAttribute(Constant.LAST_SEND_BD_MSG_NUM);
            if (!TextUtils.isEmpty(receiverNumber)) {
                address.setText(receiverNumber);
            }
            address.requestFocus();
            receiveTipTv.setVisibility(VISIBLE);
        }else{
            address.setText(receiverName);
            BoxContact.cacheFromBoxId(receiverNumber);
            address.setFocusable(false);
            receiveTipTv.setVisibility(View.GONE);
            address.setGravity(Gravity.CENTER);
        }
        initMsg();
        if(GlobalParams.rdCentreNumber.equals(receiverNumber)){
            locationInfo.setVisibility(View.GONE);
        }
        rec_width=dip2px(60);
        rec_height=dip2px(40);
        ova_width_hg=dip2px(45);
        sendBtnBlueDB=ContextCompat.getDrawable(this,R.drawable.send_msg_btn_haige);
        sendBtnGrayDB=ContextCompat.getDrawable(this,R.drawable.button_gray_bg);
        initVoiceDialog();
        initCustomContent();
        //软键盘监听
        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                if(shortcutsCB.isChecked()){
                    shortcutsCB.setChecked(false);
                }
            }

            @Override
            public void keyBoardHide(int height) {
                //键盘关闭
            }
        });
        ImgSendManager.getInstance().setSendPicCallback(this::initMsg);

        autoRefresh();
    }

    @Click//图片选择
    void picture(){
        if(!checkSend()){
            return;
        }
        ImgSendManager.getInstance().selectImg(this);
    }
    @Touch   //语音发送
    void voiceInputBtn(MotionEvent event){
        int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            if (!checkSend()) {
                return;
            }
            mVoiceDialog.isSendVoice(this);
        }
        if (mVoiceDialog.isShowing()) {
            mVoiceDialog.dialogTouch(event);
        }
    }
    @CheckedChange
    void shortcutsCB(boolean b){
        if(b){
            hideInputKeyBord();
            customLL.setVisibility(VISIBLE);
        }else{
            customLL.setVisibility(View.GONE);
        }
    }
    @CheckedChange
    void voice(boolean b){
        if(b){
            hideKeyboard();
            inputArea.setVisibility(View.GONE);
            voiceInputBtn.setVisibility(VISIBLE);
        }else{
            inputArea.setVisibility(View.VISIBLE);
            voiceInputBtn.setVisibility(View.GONE);
        }
    }

    //初始化自定义内容
    public void initCustomContent(){
        String content=sp.getAttribute(Constant.CUSTOM_CONTENT);
        String defaultMsg = "我在这里，一切正常。~a-麻烦各位队友报一下自己的位置。~a-我已经安全到达目的地";
        if(!"".equals(content)){
            content=content+"~a-"+ defaultMsg;
        }else {
            content = defaultMsg;
        }
        final String []str=content.split("~a-");
        for(final String str1:str){
            @SuppressLint("InflateParams")
            View view= LayoutInflater.from(this).inflate(R.layout.custom_item, null, false);
            TextView textName=view.findViewById(R.id.textName);
            textName.setTextColor(getColor(R.color.black));
            view.setBackground(getDrawable(R.color.white));
            view.setOnClickListener(view1 -> {
                String str2 =textName.getText().toString();
                sendMessageEdit.setText(str2);
                sendBtn();
                sendMessageEdit.setText("");
            });
            ImageView imageView=view.findViewById(R.id.del_custom);
            imageView.setVisibility(View.GONE);
            textName.setText(str1);
            customLL.addView(view);
        }
    }
    //发送消息检查方法
    public final boolean checkSend(){
        if (!BeidouBoxParams.isBoxConnectNormal) {//终端是否连接
            popupMsg(getString(R.string.please_connect_the_terminal_first));
            return false;
        }
        if(ImgSendManager.getInstance().isSend()){//图片是否发送中
            toast("图片正在发送中!");
            return false;
        }
        if (BeidouBoxParams.sentWaitSec != 0) {//频度是否足够
            popupMsg(getString(R.string.not_enough_frequency));
            return false;
        }
        int bdSignal = BeidouBoxParams.getBdSignal();
        if (bdSignal < sendBeidouMsgSignalEnable) {//信号是否良好
            MainApp.getInstance().showMsg(getString(R.string.please_move_the_terminal_location));
            return false;
        }
        if (entryMode == 0) {//判断是否是新的发送消息页面
            receiverNumber =  getTextStr(address);
            if ("".equals(receiverNumber)) {
                popupMsg(getString(R.string.please_enter_recipient_card_number));
                return false;
            }
            // 因为设置了最大长度 7 ，所以这里的判读就控制到了 6或7位
            if (receiverNumber.length() < 6) {
                popupMsg(getString(R.string.receiver_card_number_format_is_incorrect));
                return false;
            }
        }
        return  true;
    }


    private final int SELECT_CONTACT_CODE=3;

    @Click(R.id.choose_contact_img)
    void chooseConTactImg(){
        Intent intent=new Intent();
        intent.setClass(this, AddressBookActivity_.class);
        intent.putExtra("entryMode",1);
        startActivityForResult(intent,SELECT_CONTACT_CODE);
    }
    @OnActivityResult(SELECT_CONTACT_CODE)
    void selectContactResult(int resultCode, Intent data){
        if(resultCode==RESULT_OK){
            String receiverNumber=data.getStringExtra("receiverNumber");
            address.setText(receiverNumber);
        }
    }
    @Click
    void sendBtn(){
        if(!checkSend()){
            return;
        }
        String content=getTextStr(sendMessageEdit);
        if (content == null || content.equals("")) {
            popupMsg("发送内容不能为空");
            return;
        }
        try {
            if (entryMode == Constant.ENTRY_SEND_CENTER_NUMBER || GlobalParams.rdCentreNumber.equals(receiverNumber)) {//是否发送指挥中心
                senBdCenterMsg(content, Constant.TEXT, 0);
            } else {
                sendBdMsg(content, Constant.TEXT, 0);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    // TODO：后期整合二个方法
    //发送消息
    void sendBdMsg(String content,int msgType,int seconds){
        if(shortcutsCB.isChecked()){
            shortcutsCB.setChecked(false);
        }
        UserMessageVO userMessage = new UserMessageVO();
        userMessage.setSendTime(DateUtils.getDateLongSerial());
        userMessage.setSendNumber(BeidouBoxParams.userCardNumber);
        userMessage.setReceiverNumber(receiverNumber);
        userMessage.setMsgType(msgType);
        userMessage.setSeconds(seconds);
        userMessage.setContent(content);
        userMessage.setIoType(Constant.SEND_MESSAGE);
        userMessage.setRead(true);
        userMessage.setStatus(Constant.SEND_MSG_WAIT);
        String bdMsg="";
        int type=2;
        if(msgType==Constant.TEXT) {
            type=3;
            if (locationInfo.isChecked()) {
                userMessage=setUserLoc(userMessage);
                userMessage.setContent(content);
            }
            bdMsg = ConvertToBdMsgTool.castUserMessageToA4(userMessage,locationInfo.isChecked());
        }else if(msgType==Constant.AUDIO){
            bdMsg = ConvertToBdMsgTool.castUserMessageTo0xA7(userMessage,null);
        }
        userMessage.insert();
        if(msgType==Constant.PICTURE) {
            ImgSendManager.getInstance().sendImg(userMessage); //todo:2
        }else{
            BdToolFactory.getBdSendBase().sendMsg(userMessage.getReceiverNumber(),frePoint,type,bdMsg);
            MainApp.getInstance().startNewSentWaitSecTimer();
            MainApp.getInstance().startSentStatusWaitSecTimer();
            BeidouBoxParams.lastMsg=userMessage;
        }
        BoxContact.cacheFromBoxId(receiverNumber,msgType,content,true);
        sp.addAttribute(Constant.LAST_SEND_BD_MSG_NUM, receiverNumber);
        sendMessageEdit.setText("");
        msgAdapter.notifyInsert(userMessage);
        scrollToPosition();
        //receiveMessage(bdMsg,receiverNumber);
    }
    //设置定位信息
    public UserMessageVO setUserLoc(UserMessageVO userMessage){
        //带位置
        int format=sp.getAttributeInt(Constant.LATITUDE_AND_LONGITUDE_FORMAT);
        if(Constant.DEGREE_MINUTES_SECONDS_FORMAT==format&&!"".equals(BeidouBoxParams.gpsLongitude)&&!"".equals(BeidouBoxParams.gpsLatitude)&&BeidouBoxParams.gpsLongitude.contains("°")){
            userMessage.setLongitude(StringUtil.changeToStr(BeidouBoxParams.gpsLongitude));
            userMessage.setLatitude(StringUtil.changeToStr(BeidouBoxParams.gpsLatitude));
        }else{
            userMessage.setLongitude(BeidouBoxParams.gpsLongitude);
            userMessage.setLatitude(BeidouBoxParams.gpsLatitude);
        }
        userMessage.setAltitude(String.valueOf((int)BeidouBoxParams.gpsAltitude));
        return  userMessage;
    }
    //发送到平台中心
    void senBdCenterMsg(String content,int msgType,int seconds){
        if(shortcutsCB.isChecked()){
            shortcutsCB.setChecked(false);
        }
        UserMessageVO userMessage = new UserMessageVO();
        userMessage.setSendTime(DateUtils.CalendarToString(Calendar.getInstance(), null));
        userMessage.setSendNumber(BeidouBoxParams.userCardNumber);
        //接收者号码
        userMessage.setReceiverNumber(GlobalParams.rdCentreNumber);
        userMessage.setMsgType(msgType);
        userMessage.setSeconds(seconds);
        userMessage.setContent(content);
        userMessage.setIoType(Constant.SEND_MESSAGE);
        userMessage.setRead(true);
        userMessage.setStatus(Constant.SEND_MSG_WAIT);
        String bdMsg ="";
        if(msgType==Constant.TEXT) {
            int format=sp.getAttributeInt(Constant.LATITUDE_AND_LONGITUDE_FORMAT);
            if(Constant.DEGREE_MINUTES_SECONDS_FORMAT==format&&!"".equals(BeidouBoxParams.gpsLongitude)&&!"".equals(BeidouBoxParams.gpsLatitude)){
                userMessage.setLongitude(StringUtil.changeToStr(BeidouBoxParams.gpsLongitude));
                userMessage.setLatitude(StringUtil.changeToStr(BeidouBoxParams.gpsLatitude));
            }else{
                userMessage.setLongitude(BeidouBoxParams.gpsLongitude);
                userMessage.setLatitude(BeidouBoxParams.gpsLatitude);
            }
            userMessage.setAltitude(String.valueOf((int) BeidouBoxParams.gpsAltitude));
            bdMsg = ConvertToBdMsgTool.castUserMessageTo0x93(userMessage,GlobalParams.commandCentreNumber);
        }else if(msgType==Constant.AUDIO){
            bdMsg = ConvertToBdMsgTool.castUserMessageTo0xA7(userMessage,GlobalParams.commandCentreNumber);
        }
        userMessage.insert();
        if(msgType==Constant.PICTURE) {
            ImgSendManager.getInstance().newSendImg(userMessage); //todo:2
        }else{
            BdToolFactory.getBdSendBase().sendMsg(GlobalParams.rdCentreNumber,2,2,bdMsg);
            MainApp.getInstance().startNewSentWaitSecTimer();
            MainApp.getInstance().startSentStatusWaitSecTimer();
            BeidouBoxParams.lastMsg=userMessage;
        }
        BoxContact.cacheFromBoxId(receiverNumber,msgType,userMessage.getContent(),true);
        sendMessageEdit.setText("");
        msgAdapter.notifyInsert(userMessage);
        scrollToPosition();
    }

    /**
     * 提示字数
     */
    @AfterTextChange
    void sendMessageEdit(){
        String str=sendMessageEdit.getText().toString();

        String lastContentNumString = "当前还可以输入<font color='#259FF1'>" + (max_text_size-str.length()) + "</font>个字";
        lastInputContentTv.setText(Html.fromHtml(lastContentNumString));
    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 1)
    public void eventBus(ResultNumberVo resultNumberVo){
        if(resultNumberVo==null){
            return;
        }
        if(receiverNumber!=null&&receiverNumber.equals(resultNumberVo.getNumber())){
            initMsg();
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 1)
    public void eventBus(UserMessageVO userMessage){
        //更新聊天列表
        if (userMessage!=null&&userMessage.getReceiverNumber().equals(receiverNumber)) {
            BoxContact.cacheFromBoxId(userMessage.getReceiverNumber(),userMessage.getMsgType(),userMessage.getContent(),userMessage.getLongitude(),userMessage.getLatitude(), true);
            GlobalParams.unReadNewsNum--;
        }
        initMsg();
    }
    //消息列表刷新
    public void initMsg(){
        msgList=SQLite.select().from(UserMessageVO.class).where(UserMessageVO_Table.receiverNumber.eq(receiverNumber)).queryList();
        if(msgAdapter==null){
            msgAdapter=new MsgAdapter(this,msgList);
            msgAdapter.setHasStableIds(true);
        }else{
            updateMessageList(msgList);
            return;
        }
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        messageRV.setLayoutManager(linearLayoutManager);
        messageRV.setAdapter(msgAdapter);
        linearLayoutManager.setStackFromEnd(true);
        msgAdapter.setOnItemClickListener(new MsgAdapter.OnItemClickListener() {
            @Override
            public void OnItemMapClickListener(View view, String longitude, String latitude) {
                if (chooseMapPopupWindow == null) {
                    chooseMapPopupWindow = new ChooseMapPopupWindow(SendMsgActivity.this, longitude, latitude, SendMsgActivity.this);
                } else {
                    chooseMapPopupWindow.setLonLat(longitude, latitude);
                }
                chooseMapPopupWindow.show();
            }
            @Override
            public void OnItemResendClickListener(View view, UserMessageVO userMessage) {
                // new CustomDialog(SendMsgActivity.this, "是否重新发送", CustomDialog.DEL_DIALOG, (dialog, content, view1) -> resendMsg(userMessage)).show();
                resendMsg(userMessage);
            }

            @Override
            public void showPicProgress(TextView picSize, TextView alreadySent, TextView postTheRest, TextView nextSend) {
                currentPicSize=picSize;
                currentAlreadySent=alreadySent;
                currentPostTheRest=postTheRest;
                currentNextSend=nextSend;
            }

            @Override
            public void viewPic(String path) {
                Intent intent=new Intent();
                intent.setClass(SendMsgActivity.this,ChatViewPictureActivity_.class);
                intent.putExtra("filePath",path);
                startActivity(intent);
            }

            @Override
            public void onDel(UserMessageVO userMessage, boolean isScr) {
                initMsg();
            }
        });
    }
    public void resendMsg(UserMessageVO userMessage){
        if(!checkSend()){
            return;
        }
        if(userMessage.getMsgType()==Constant.TEXT){
            userMessage.setStatus(Constant.SEND_MSG_WAIT);
            String content=userMessage.getContent();
            String bdMsg="";
            int type=2;
            if (entryMode == Constant.ENTRY_SEND_CENTER_NUMBER || GlobalParams.rdCentreNumber.equals(receiverNumber)) {//是否发送指挥中心
                userMessage=setUserLoc(userMessage);
                bdMsg = ConvertToBdMsgTool.castUserMessageTo0x93(userMessage,GlobalParams.commandCentreNumber);
                TerminalSendManager.getInstance().levelThreeGetCCTCQ(GlobalParams.rdCentreNumber,2,2,bdMsg);
            }else{
                type=3;
                if (locationInfo.isChecked()) {
                    userMessage=setUserLoc(userMessage);
                    userMessage.setContent(content);
                }
                bdMsg = ConvertToBdMsgTool.castUserMessageToA4(userMessage,locationInfo.isChecked());
                TerminalSendManager.getInstance().levelThreeGetCCTCQ(userMessage.getReceiverNumber(),frePoint,type,bdMsg);
            }
            userMessage.update();
            MainApp.getInstance().startNewSentWaitSecTimer();
            MainApp.getInstance().startSentStatusWaitSecTimer();
            BeidouBoxParams.lastMsg=userMessage;
            initMsg();
        }else{
            toast("暂时只支持文字重新发送");
        }
    }
    private TextView currentPicSize;
    private TextView currentAlreadySent;
    private TextView currentPostTheRest;
    private TextView currentNextSend;
    //todo：后期调整
    public void initPicProgress(){
        int index=ImgSendManager.getInstance().currentSendImgDataVO.getId()+1;
        int currentSeconds=index*(sendFreq+ImgSendManager.delaySeconds);
        String picSizeStr="<font color='#4682b4'>图片大小</font> <font color='#ff0000'>"+ImgSendManager.getInstance().totalSize+"</font> <font color='#4682b4'>KB</font>";
        currentPicSize.setText(Html.fromHtml(picSizeStr));
        String alreadySentStr = "<font color='#4682b4'>已发送</font>  <font color='#ff0000'>" +
                index +
                "</font> <font color='#4682b4'>/共</font> <font color='#ff0000'>" +
                ImgSendManager.getInstance().currentSize +
                "</font> <font color='#4682b4'>条报文</font>";
        currentAlreadySent.setText(Html.fromHtml(alreadySentStr));

        String postTheRestStr = "<font color='#4682b4'>离发送完剩余约</font><font color='#ff0000'>" +
                (ImgSendManager.getInstance().totalSeconds - currentSeconds) +
                "</font>  <font color='#4682b4'>秒</font>";
        currentPostTheRest.setText(Html.fromHtml(postTheRestStr));

        String nextSendStr = "</font><font color='#4682b4'>下一条发送时间为</font><font color='#ff0000'>" +
                BeidouBoxParams.sentWaitSec +
                "</font><font color='#4682b4'>秒</font>";
        currentNextSend.setText(Html.fromHtml(nextSendStr));
    }
    @Click
    void headLeft(){
        hideKeyboard();
        setResult(Activity.RESULT_OK);
        finish();
    }

    //是否移动到底部
    private final boolean isScrollToBottom = true;
    /**
     * 更新消息列表
     *
     */
    private void updateMessageList(final List<UserMessageVO> list) {
        runOnUiThread(() -> {
            if (list != null) {
                msgAdapter.notifyData(list);
                scrollToPosition();
            }
        });
    }
    public void scrollToPosition(){
        if (isScrollToBottom) {
            messageRV.getLayoutManager().scrollToPosition(messageRV.getAdapter().getItemCount() - 1);
        }
    }
    /**
     * 刷新终端信息
     */
    private void refreshStatus() {
        if(ImgSendManager.getInstance().isSend()&&currentPicSize!=null){
            initPicProgress();
            setSendBtn(false,"发送中",sendBtnGrayDB,rec_width,rec_height);
        }else{
            if (BeidouBoxParams.isBoxConnectNormal) {
                int bdSignal = BeidouBoxParams.getBdSignal();
                if (BeidouBoxParams.sentWaitSec > 0) {
                    setSendBtn(false,BeidouBoxParams.sentWaitSec + "s",sendBtnGrayDB,rec_width,rec_height);
                }else if (bdSignal < sendBeidouMsgSignalEnable) {
                    setSendBtn(false,"无信号",sendBtnGrayDB,rec_width,rec_height);
                }else{
                    setSendBtn(true,"",sendBtnBlueDB,ova_width_hg,ova_width_hg);
                }
            } else {
                setSendBtn(false,"未连接",sendBtnGrayDB,rec_width,rec_height);
            }
        }
        locationInfo.setText(MessageFormat.format("发送携带位置：经度：{0}纬度:{1}", BeidouBoxParams.gpsLongitude, BeidouBoxParams.gpsLatitude));
    }
    /**
     * 自动刷新
     */
    private void autoRefresh() {
        if (isRefreshing) {
            return;
        }
        isRefreshing = true;
        new Thread(() -> {
            try {
                while (isRefreshing) {
                    Message msg = new Message();
                    msg.what = 1;
                    adapterHandler.sendMessage(msg);
                    sleep(1000);
                }
            } catch (Exception e) {
                Log.e("InfoMessage", e.toString());
            }
        }).start();
    }
    /**
     * 刷新UI
     */
    @SuppressLint("HandlerLeak")
    private final Handler adapterHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                refreshStatus();
            }
        }
    };
    public void setSendBtn(boolean isClick, String text, Drawable drawable,int width,int height){
        sendBtn.setClickable(isClick);
        sendBtn.setText(text);
        sendBtn.setBackground(drawable);
        ViewGroup.LayoutParams layoutParams=sendBtn.getLayoutParams();
        layoutParams.width=width;
        layoutParams.height=height;
        sendBtn.setLayoutParams(layoutParams);
    }
    private void initVoiceDialog(){
        mVoiceDialog=new VoiceDialog(this, (dialog, audioFilePath) -> {
            int seconds= FileUtils.getPcmSeconds(audioFilePath);
            if(1>=seconds){
                toast("录音时间太短！");
            }else{
                if(entryMode==Constant.ENTRY_SEND_CENTER_NUMBER){//是否发送指挥中心
                    senBdCenterMsg(audioFilePath,Constant.AUDIO,seconds);
                }else{
                    sendBdMsg(audioFilePath,Constant.AUDIO,seconds);
                }
            }
            if(dialog.isShowing()){
                dialog.dismiss();
            }
        });
    }
    //模拟接收
    public void receiveMessage(String content,String fromNumber){
        BDTXInfo bdtxInfo=new BDTXInfo();
        bdtxInfo.content=content;
        bdtxInfo.fromNumber=Integer.parseInt(fromNumber);
        bdtxInfo.messageType=1;
        UserMessageVO userMessageVO = ConvertToUserMsgTool.convertMessage(bdtxInfo);
        if(userMessageVO!=null){
            userMessageVO.insert();
            BoxContact.cacheFromBoxId(String.valueOf(bdtxInfo.fromNumber),userMessageVO.getMsgType(),userMessageVO.getContent(),userMessageVO.getLongitude(),userMessageVO.getLatitude(),false);
            EventBus.getDefault().post(userMessageVO);
        }
    }

    @Override
    public void onBackPressed() {
        setResult(Activity.RESULT_OK);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hideInputKeyBord();
        if (chooseMapPopupWindow != null) {
            chooseMapPopupWindow.dismiss();
        }
    }

    @Override
    public void sendMsg(String map, String longitude, String latitude) {
        GeoPoint latlon = new GeoPoint(Double.parseDouble(latitude), Double.parseDouble(longitude));
        Intent mIntent = new Intent();
        switch (map) {
            case "baidu":
                //百度地图(地球坐标系)
                mIntent.setPackage("com.baidu.BaiduMap");
                break;
            case "gaode":
                //高德地图(地球坐标系)
                mIntent.setPackage("com.autonavi.minimap");
                break;
            case "tengxun":
                //腾讯地图(火星坐标系)
                latlon = BDToGPS.castToOtherPoint(latlon, 1);
                mIntent.setPackage("com.tencent.map");
                break;
            case "othermap:":
                //其他地图统一用地球坐标系
                break;
            default:
                break;
        }
        @SuppressLint("DefaultLocale")
        String point = String.format("geo:%f,%f", latlon.getLatitude(), latlon.getLongitude());
        Uri mUri = Uri.parse(point);
        mIntent.setAction(Intent.ACTION_VIEW);
        mIntent.setData(mUri);
        try {
            startActivity(mIntent);
        } catch (Exception e) {
            Toast.makeText(this, "没有找到可用的地图应用", Toast.LENGTH_SHORT).show();
        }
        chooseMapPopupWindow.hide();
        chooseMapPopupWindow = null;
    }
    @Override
    protected void onPause() {
        super.onPause();
        if (AudioTrackManager.getInstance().isStart()) {
            AudioTrackManager.getInstance().stopPlay();
        }
    }
    @OnActivityResult(ImgSendManager.SELECT_PICK_CODE)
    public void selectPick(int resultCode,Intent data){
        if(resultCode==Activity.RESULT_OK){
            if(data==null){
                return;
            }
            // 选择到图片的uri
            Uri uri = data.getData();
            // 第一种方式，使用文件路径创建图片
            // 文件路径的列
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            // 获取图片的游标
            assert uri != null;
            Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
            assert cursor != null;
            cursor.moveToFirst();
            // 获取列的指针
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            // 根据指针获取图片路径
            String path = cursor.getString(columnIndex);
            Intent intent2=new Intent();
            intent2.setClass(this,PictureViewActivity_.class);
            intent2.putExtra("path",path);
            startActivityForResult(intent2,ImgSendManager.PICK_PIC);
        }
    }
    @OnActivityResult(ImgSendManager.PICK_PIC)
    public void pickPic(int resultCode,Intent data){
        if(resultCode==Activity.RESULT_OK){
            String savePath=data.getStringExtra("saveFile");
            if(entryMode==Constant.ENTRY_SEND_CENTER_NUMBER||GlobalParams.rdCentreNumber.equals(receiverNumber)){//是否发送指挥中心
                senBdCenterMsg(savePath,Constant.PICTURE,0);
            }else{
                sendBdMsg(savePath,Constant.PICTURE,0);
            }

        }
    }
    @OnActivityResult(ImgSendManager.CAMERA)
    public void camera(int resultCode){
        if(resultCode==Activity.RESULT_OK){
            String imgUrl=ImgSendManager.cameraPath;
            Intent intent=new Intent();
            intent.setClass(this,PictureViewActivity_.class);
            intent.putExtra("path",imgUrl);
            startActivityForResult(intent,ImgSendManager.PICK_PIC);
        }
    }
    @AfterTextChange(R.id.receive_address_edit)
    void  address(){
        if(entryMode==0){
            receiverNumber = getTextStr(address);
            //获取用户消息
            initMsg();
        }
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        // TextView tvSend = chatKeyboard.getTvSend();tvSend为发送按钮
        int[] leftTop = {0, 0};
        //获取输入框当前的location位置
        sendBtn.getLocationInWindow(leftTop);
        int left = leftTop[0];
        int top = leftTop[1];
        int bottom = top + sendBtn.getHeight();
        int right = left + sendBtn.getWidth();
        int x = (int)event.getX();
        int y = (int)event.getY();
        if (x > left && x < right && y > top && y < bottom) {
            // 点击的是发送按钮，保留点击EditText的事件
            // 必不可少，否则所有的组件都不会有TouchEvent了
            if (getWindow().superDispatchTouchEvent(event)) {
                return true;
            }
            return onTouchEvent(event);
        }
        handlerOtherTypeDispatchTouchEvent(event);
        return false;
    }
    private boolean handlerOtherTypeDispatchTouchEvent(MotionEvent event) {
        int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, event)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(event);
        } else if (action == MotionEvent.ACTION_MOVE) {

        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(event)) {
            return true;
        }
        return onTouchEvent(event);
    }
    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                //使EditText触发一次失去焦点事件
                v.setFocusable(false);
                v.setFocusableInTouchMode(true);
                return true;
            }
        }
        return false;
    }


}

